「GitHub Actions を使用して開発タスクを自動化する」 オンライントレーニングを受講してみた

「GitHub Actions を使用して開発タスクを自動化する」 オンライントレーニングを受講してみた

Clock Icon2024.08.24

本記事では、Microsoft Learn の無料オンライントレーニング「GitHub Actions を使用して開発タスクを自動化する」の内容を紹介します。また、学んだ内容を CI/CD のローカル実行テストツール(act)で実践した経験についても共有します。

Microsoft Learn とは

Microsoft Learn は、Microsoft が提供する無料のオンライン学習プラットフォームです。個人や組織向けに、幅広い技術トピックについてのトレーニングコンテンツを提供しています。

https://learn.microsoft.com/ja-jp/training/

今回は GitHub Actions を基礎を学ぶべく初学者向けのトレーニングを受講しました。

https://learn.microsoft.com/ja-jp/training/modules/github-actions-automate-tasks/

トレーニングの概要

このトレーニングは、GitHub Actions の基本を学び、実際にワークフローを作成して実行するまでを体験できるハンズオン形式のコースです。

学習内容

トレーニングは座学と実技の 2 部構成になっています。

  1. 座学パート:
    • GitHub Actions の概要
    • ワークフローの構成要素
  2. 実技パート:
    • 基本的なワークフローの作成
    • ワークフローの実行と動作確認

座学パート

座学パートでは、GitHub Actions の基礎を学びます。はじめて Microsoft Learn のトレーニングを受講したのですが、読みやすい日本語訳、一部要素は図解もあり学習コンテンツとしては良質でした。

GitHub_Actions_のコンポーネントを特定する_-_Training___Microsoft_Learn
出典: トレーニング資料より

実技パート

実技パートでは、プルリクエストが作成されたときに自動的に「Welcome to the repository!」というコメントを追加するワークフローを作成します。実技パートからは日本語訳の提供はなく英語です。

Update_README_md_by_bigmuramura_·_Pull_Request__2_·_bigmuramura_hello-github-actions

以下は作成したワークフローの詳細です。

  • プルリクエストが開かれたときにトリガーされる
  • gh CLI コマンドを使用してコメントを投稿
  • プルリクエストの URL は Webhook イベントで取得可能
作成したワークフローファイル
name: Post welcome comment
on:
  pull_request:
    types: [opened]
permissions:
  pull-requests: write
jobs:
  build:
    name: Post welcome comment
    runs-on: ubuntu-latest
    steps:
      - run: gh pr comment $PR_URL --body "Welcome to the repository!"
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          PR_URL: ${{ github.event.pull_request.html_url }}

実際にプルリクエストを作成し、ワークフローが正常に実行されることを確認してトレーニングは完了です。

act を利用してローカル環境で実践

次に、act を使用してローカル環境でトレーニングで作成したワークフローを実行してみます。

https://dev.classmethod.jp/articles/act-for-github-actions-local-execution-tool/

初回実行と問題点

まず、作成したジョブの ID を確認します。ジョブ ID はbuildであることが確認できました。

$ act --job build --list
INFO[0000] Using docker host 'unix:///var/run/docker.sock', and daemon socket 'unix:///var/run/docker.sock'
Stage  Job ID  Job name              Workflow name         Workflow file  Events
0      build   Post welcome comment  Post welcome comment  welcome.yml    pull_request

次に、実際に実行してみます。

$ act pull_request --job build -v
---省略---
[Post welcome comment/Post welcome comment] [DEBUG] Working directory '/Users/ohmura.yasutaka/github/bigmuramra/hello-github-actions'
| /var/run/act/workflow/0: line 2: gh: command not found

実行結果から、gh コマンドが見つからないことがわかりました。これは、act の標準的なイメージ(Medium)が GitHub Actions の環境と完全な互換性を持っていないためです。

:::message 注意点 act には Large イメージも用意されていますが、約 20GB と非常に大きいため、今回は gh コマンドのみを追加したカスタムイメージを作成して対応します。 :::

カスタムイメージを作成して実行

gh コマンドを含むカスタムイメージを作成するために、以下の Dockerfile を使用します。

  1. catthehacker/ubuntu:act-latest をベースイメージとして使用
  2. 必要なパッケージをインストールし、GitHub CLI の公式リポジトリを追加
  3. gh コマンドをインストール
FROM catthehacker/ubuntu:act-latest

RUN apt-get update && apt-get install -y \
    curl \
    && curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \
    && echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | tee /etc/apt/sources.list.d/github-cli.list > /dev/null \
    && apt-get update \
    && apt-get install -y gh

イメージをビルドします。

$ docker buildx build --platform linux/amd64 -t my-act-image:latest .

作成したカスタムイメージを使用してワークフローを実行します。ローカルのイメージを使用するため--pull=falseを指定することがポイントでした。

$ act --job build -P ubuntu-latest=my-act-image:latest --pull=false
中略
[Post welcome comment/Post welcome comment]   🐳  docker exec cmd=[bash --noprofile --norc -e -o pipefail /var/run/act/workflow/0] user= workdir=
| gh: To use GitHub CLI in a GitHub Actions workflow, set the GH_TOKEN environment variable. Example:
|   env:
|     GH_TOKEN: ${{ github.token }}
[Post welcome comment/Post welcome comment]   ❌  Failure - Main gh pr comment $PR_URL --body "Welcome to the repository!"
[Post welcome comment/Post welcome comment] exitcode '4': failure
[Post welcome comment/Post welcome comment] 🏁  Job failed

GitHub トークンが設定されていないことがわかりました。次のステップでこの問題に対処します。

試行錯誤した結果

初回実行の失敗を踏まえ、ワークフローファイルと act の実行コマンドを以下のように修正しました。

修正したワークフローファイル
name: Post welcome comment
on:
  pull_request:
    types: [opened]
permissions:
  pull-requests: write
jobs:
  build:
    name: Post welcome comment
    runs-on: ubuntu-latest
    steps:
      - run: gh pr comment $PR_URL --body "Welcome to the repository!"
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          # PR_URL: ${{ github.event.pull_request.html_url }}
          PR_URL: ${{ env.PR_URL }}

修正後の act コマンドは以下です。GitHub トークンは-s指定で渡すのが手軽で良かったです。

$ act pull_request --job build \
  -P ubuntu-latest=my-act-image:latest \
  --pull=false \
  -s GITHUB_TOKEN="$(gh auth token)" \
  --env PR_URL="https://github.com/bigmuramura/hello-github-actions/pull/2"
実行結果
INFO[0000] Using docker host 'unix:///var/run/docker.sock', and daemon socket 'unix:///var/run/docker.sock'
[Post welcome comment/Post welcome comment] 🚀  Start image=my-act-image:latest
[Post welcome comment/Post welcome comment]   🐳  docker pull image=my-act-image:latest platform=linux/amd64 username= forcePull=false
[Post welcome comment/Post welcome comment]   🐳  docker create image=my-act-image:latest platform=linux/amd64 entrypoint=["tail" "-f" "/dev/null"] cmd=[] network="host"
[Post welcome comment/Post welcome comment]   🐳  docker run image=my-act-image:latest platform=linux/amd64 entrypoint=["tail" "-f" "/dev/null"] cmd=[] network="host"
[Post welcome comment/Post welcome comment]   🐳  docker exec cmd=[node --no-warnings -e console.log(process.execPath)] user= workdir=
[Post welcome comment/Post welcome comment] ⭐ Run Main gh pr comment $PR_URL --body "Welcome to the repository!"
[Post welcome comment/Post welcome comment]   🐳  docker exec cmd=[bash --noprofile --norc -e -o pipefail /var/run/act/workflow/0] user= workdir=
https://github.com/bigmuramura/hello-github-actions/pull/2#issuecomment-2306699819
[Post welcome comment/Post welcome comment]   ✅  Success - Main gh pr comment $PR_URL --body "Welcome to the repository!"
[Post welcome comment/Post welcome comment] Cleaning up container for job Post welcome comment
[Post welcome comment/Post welcome comment] 🏁  Job succeeded

Update_README_md_by_bigmuramura_·_Pull_Request__2_·_bigmuramura_hello-github-actions-2

まとめ

座学だけでなく、実際にワークフローを作成・GitHub Actions の実行を体験できる手軽なハンズオントレーニングでした。

おわりに

Microsoft Learn のトレーニングを通じて GitHub Actions の基礎を学び、さらに act を使用してローカル環境での実践を試みました。act の使用はまだ学習段階であり、完全に使いこなせているわけではありませんが、この経験を通じて以下の点を実感しました。

  • ローカルでのワークフロー検証の重要性
  • 実際の GitHub Actions の環境と完全に一致させることの難しさ

GitHub Actions 関連のトレーニングは他にも提供されているためトライしてみようと思います。

https://learn.microsoft.com/ja-jp/training/browse/?products=github&terms=actions

参考

この記事をシェアする

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.